package com.wstuo.common.tools.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.wstuo.common.tools.dao.IInstantMessageDAO;
import com.wstuo.common.tools.dto.InstantMessageDTO;
import com.wstuo.common.tools.dto.InstantMessageQueryDTO;
import com.wstuo.common.tools.dto.MessageConsumerDTO;
import com.wstuo.common.tools.entity.InstantMessage;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.util.StringUtils;

/**
 * 即时信息Service类
 * 
 * @author QXY
 */
public class InstantMessageService implements IInstantMessageService {
	/**
	 * Injection InstantMessageDAO
	 */
	@Autowired
	private IInstantMessageDAO instantmessageDAO;
	@Autowired
	private IUserDAO userDAO;
	@Autowired
	private AppContext appctx;

	/**
	 * 查询全部信息
	 * 
	 * @return List<InstantMessageDTO>
	 */
	@Transactional
	public List<InstantMessageDTO> findAllInstantMessage() {
		List<InstantMessage> entites = instantmessageDAO.findAll();
		List<InstantMessageDTO> dtos = new ArrayList<InstantMessageDTO>(entites.size());

		for (InstantMessage entity : entites) {
			InstantMessageDTO dto = new InstantMessageDTO();

			entity2dto(entity, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
	 * 根据标题查询全部信息
	 * 
	 * @param title
	 * @return List<InstantMessageDTO>
	 */
	@Transactional
	public List<InstantMessageDTO> findAllIMLikeTitle(String title) {
		List<InstantMessage> instantmessage = instantmessageDAO.findByKeyWord(title);
		List<InstantMessageDTO> dtos = new ArrayList<InstantMessageDTO>(instantmessage.size());

		for (InstantMessage entity : instantmessage) {
			InstantMessageDTO dto = new InstantMessageDTO();

			entity2dto(entity, dto);
			dtos.add(dto);
		}

		return dtos;
	}

	/**
	 * save
	 * 
	 * @param receiveUsers
	 * @param imDTO
	 * @param dto
	 * @return
	 */
	@Transactional
	public String saveInstantMessage(String[] receiveUsers, InstantMessageDTO imDTO) {

		if (receiveUsers != null && receiveUsers.length > 0) {

			for (String user : receiveUsers) {
				if (StringUtils.hasText(user)) {
					imDTO.setSendTime(new Date());
					//imDTO.setReceiverFullName(user);
					imDTO.setReceiveUsers(user);
					imDTO.setSendUsers(appctx.getCurrentLoginName());
					saveInstantMessage(imDTO);

				}
			}

			return "success";
		} else {

			throw new ApplicationException("ERROR_IM_RECEIVE_NULL");
		}
	}
	
	@Transactional
	public void sendIM(MessageConsumerDTO messageConsumerDTO) {
		for (String to : messageConsumerDTO.getTo()) {
			InstantMessageDTO dto = new InstantMessageDTO();
			dto.setContent(messageConsumerDTO.getContent());
			dto.setTitle(messageConsumerDTO.getSubject());
			dto.setSendUsers("system");
			dto.setReceiveUsers(to);
			dto.setSendTime(new Date());
			dto.setEventType(messageConsumerDTO.getModule());
			dto.setRequestEno(messageConsumerDTO.getRelateEno());
			dto.setStatus("0");
			saveInstantMessage(dto);
		}
	}

	/**
	 * 保存信息
	 * 
	 * @param dto
	 */
	@Transactional
	public void saveInstantMessage(InstantMessageDTO dto) {
		InstantMessage entity = new InstantMessage();

		dto2entity(dto, entity);
		/*if (dto.getReceiverFullName() != null) {
			User user = userDAO.findUniqueBy("loginName", dto.getReceiverFullName());
			if (user != null) {
				entity.setReceiveUsers(user.getLoginName());
			}
		}*/
		if(dto.getReceiveUsers() != null){
			User user = userDAO.findUniqueBy("loginName", dto.getReceiveUsers());
			if (user != null) {
				entity.setReceiveUsers(user.getLoginName());
			}
		}

		/*if (dto.getSenderFullName() != null) {
			User user = userDAO.findUniqueBy("fullName", dto.getSenderFullName());
			if (user != null) {
				entity.setSendUsers(user.getLoginName());
			}
		} else {
			entity.setSenderFullName(dto.getSendUsers());
		}*/
		
		if(dto.getSendUsers()  != null){
			User user = userDAO.findUniqueBy("loginName", dto.getSendUsers());
			if (user != null) {
				entity.setSendUsers(user.getLoginName());
			}
		}

		entity.setDwrStatus("0");
		entity.setImType("instant");
		instantmessageDAO.save(entity);
		dto.setImId(entity.getImId());
	}

	/**
	 * 删除即时信息
	 * 
	 * @param id
	 *            要删除的数组
	 */
	@Transactional
	public void removeInstantMessage(Long[] id) {
		instantmessageDAO.deleteByIds(id);
	}

	@Transactional
	public void updateInstantMessage(Long[] ids, String[] receiveUsers, InstantMessageDTO imDTO) {
		for (Long imid : ids) {
			InstantMessage itm = findInstantMessageById(imid);
			InstantMessageDTO itmDto = new InstantMessageDTO();
			InstantMessageDTO.entity2dto(itm, itmDto);
			itmDto.setStatus("2");
			updateInstantMessage(itmDto);
			// 回复信息
			for (String user : receiveUsers) {
				imDTO.setReceiverFullName(user);
				imDTO.setReceiveUsers(user);
				imDTO.setSendTime(new Date());
				imDTO.setSendUsers(appctx.getCurrentLoginName());
				saveInstantMessage(imDTO);
			}
		}
	}

	/**
	 * 修改即时信息
	 * 
	 * @param dto
	 */
	@Transactional
	public void updateInstantMessage(InstantMessageDTO dto) {
		InstantMessage entity = instantmessageDAO.findById(dto.getImId());
		if (dto.getTitle() != null) {
			entity.setTitle(dto.getTitle());
		}
		if (dto.getContent() != null) {
			entity.setContent(dto.getContent());
		}
		if (dto.getRemarks() != null) {
			entity.setRemarks(dto.getRemarks());
		}
		if (dto.getDescription() != null) {
			entity.setDescription(dto.getDescription());
		}
		if (dto.getStatus() != null) {
			entity.setStatus(dto.getStatus());
		}
		if (dto.getIsReadRequest() != null) {
			entity.setIsReadRequest(dto.getIsReadRequest());
		}
		instantmessageDAO.merge(entity);
	}

	/**
	 * 即时信息分页查询
	 * 
	 * @param immanageQueryDTO
	 * @param start
	 * @param limit
	 * @param sidx
	 * @param sord
	 * @return PageDTO
	 */
	@Transactional
	public PageDTO findPagerIM(InstantMessageQueryDTO immanageQueryDTO, int start, int limit, String sidx, String sord) {
		PageDTO p = instantmessageDAO.findPager(immanageQueryDTO, start, limit, sidx, sord);
		List<InstantMessage> instantmessage = (List<InstantMessage>) p.getData();
		List<InstantMessageDTO> dtos = new ArrayList<InstantMessageDTO>(instantmessage.size());
		for (InstantMessage entity : instantmessage) {
			InstantMessageDTO dto = new InstantMessageDTO();
			entity2dto(entity, dto);
			User sendUser = userDAO.findUniqueBy("loginName", dto.getSendUsers());
			if(sendUser!=null){
				dto.setSenderFullName(sendUser.getFullName());
			}
			//User receiveUser = userDAO.findUniqueBy("loginName", dto.getReceiveUsers());
			//dto.setReceiverFullName(receiveUser.getFullName());
			dtos.add(dto);
		}
		p.setData(dtos);

		return p;
	}

	/**
	 * 未读信息
	 * 
	 * @return int
	 */
	@SuppressWarnings("null")
	@Transactional
	public int findUnreadIM() {
		int sum = instantmessageDAO.findUnread();
		return sum;
	}

	/**
	 * DTO ConversionEntity
	 */
	@Transactional
	public static void dto2entity(InstantMessageDTO dto, InstantMessage entity) {
		try {
			BeanUtils.copyProperties(entity, dto);
		} catch (Exception ex) {
			throw new ApplicationException(ex);
		}
	}

	/**
	 * Entity Conversion DTO
	 */
	@Transactional
	public static void entity2dto(InstantMessage entity, InstantMessageDTO dto) {
		try {
			BeanUtils.copyProperties(dto, entity);
		} catch (Exception ex) {
			throw new ApplicationException(ex);
		}
	}

	/**
	 * 根据即时信息ID获取
	 * 
	 * @param id
	 * @return InstantMessage
	 */
	@Transactional
	public InstantMessage findInstantMessageById(Long id) {
		return instantmessageDAO.findById(id);
	}

	/**
	 * 根据即时信息ID获取InstantMessageDTO
	 * 
	 * @param id
	 * @return InstantMessage
	 */
	@Transactional
	public InstantMessageDTO findInstantMessageDTOById(Long id) {
		InstantMessageDTO dto = new InstantMessageDTO();
		InstantMessage entity = instantmessageDAO.findById(id);
		InstantMessageDTO.entity2dto(entity, dto);
		return dto;
	}

	/**
	 * 更新弹屏发送状态
	 */
	@Transactional
	public void updateDwrSendStatus(List<InstantMessage> lis) {
		for (InstantMessage entity : lis) {
			entity.setDwrStatus("1");
			instantmessageDAO.update(entity);
		}
	}

	/**
	 * 根据接受用户Id查询消息
	 * 
	 * @param userId
	 * @return List<InstantMessage>
	 */
	@Transactional
	public List<InstantMessage> findByUserId(Long userId) {
		User user = userDAO.findById(userId);
		InstantMessageQueryDTO qdto = new InstantMessageQueryDTO();
		qdto.setReceiveUsers(user.getLoginName());
		qdto.setStatus("0");
		PageDTO pageDTO = instantmessageDAO.findPager(qdto, 0, 1000, "sendTime", "desc");
		final List<InstantMessage> lis = (List<InstantMessage>) pageDTO.getData();
		return lis;
	}
}
